package com.bustle.commons.data.jpa;

import java.util.List;

import javax.persistence.EntityManager;

import com.bustle.commons.data.dao.Dao;

abstract public class JpaDao<KeyType, Type> implements Dao<KeyType, Type>
{
  abstract protected EntityManager getEntityManager();

  protected JpaDao(Class<? extends Type> aClass)
  {
    type = aClass;
  }

  @Override
  public void create(Type anObject)
  {
    getEntityManager().persist(anObject);
  }

  @Override
  public Type retrieve(KeyType aKey)
  {
    return getEntityManager().find(type, aKey);
  }

  @Override
  public List<Type> retrieveAll()
  {
    String className = type.getName().substring(type.getName().lastIndexOf(".") + 1);
    List<Type> list = getEntityManager().createQuery("from " + className).getResultList();
    return list;
  }

  @Override
  public void update(Type anObject)
  {
    getEntityManager().merge(anObject);
  }

  @Override
  public void delete(KeyType aKey)
  {
    getEntityManager().remove(retrieve(aKey));
  }

  protected Class<? extends Type> type;
}
